package com.rocksdata.mc;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;

import com.alibaba.fastjson.JSON;
import com.baidu.location.BDLocation;
import com.ctz.commonframe.ui.BaseApplication;
import com.ctz.commonframe.ui.WebViewActivity;
import com.ctz.commonframe.utils.Logger;
import com.rocksdata.mc.business.location.BaiduLocationListener;
import com.rocksdata.mc.business.location.LocationBean;
import com.rocksdata.mc.business.location.LocationInfo;
import com.rocksdata.mc.business.location.LocationManager;
import com.rocksdata.mc.business.location.UnreadManager;
import com.rocksdata.mc.entity.UnreadCache;
import com.rocksdata.mc.ui.activity.LoginActivity;
import com.rocksdata.mc.business.BusinessInterface;
import com.rocksdata.mc.business.BusinessManager;

import java.util.List;

/**
 * Created by 陈堂正 on 2016/11/24.
 */
public class MobileCampusApplication extends BaseApplication {
    @SuppressLint("StaticFieldLeak")
    private static Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
        Logger.enableLog(BuildConfig.LOG_DEBUG);
        BusinessInterface.IPushManager pushManager = BusinessManager.getPushManager();
        if (pushManager != null)
            pushManager.initPushService();
        // 初始化百度地图组件
//        SDKInitializer.initialize(this);
//        ChatHelper.getInstance().init(context);

//        RongyunChatManager.init(context);

        // 为了解决第三方activity沉浸式标题栏和系统状态栏重叠的问题
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks(){

            @Override
            public void onActivityStopped(Activity activity) {

            }

            @Override
            public void onActivityStarted(Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }

            @Override
            public void onActivityResumed(Activity activity) {

            }

            @Override
            public void onActivityPaused(Activity activity) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {

            }

            @TargetApi(Build.VERSION_CODES.KITKAT)
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                Window win = activity.getWindow();
                if(!activity.getClass().getCanonicalName().startsWith(getPackageName())){
                    win.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                }
            }
        });

        WebViewActivity.setOnWebViewEventListener(new WebViewActivity.OnWebViewEventListener() {
            @Override
            public void onRelogin() {
                final WebViewActivity instance = WebViewActivity.getInstance();
                if (instance == null) return;
                BusinessManager.getAccountManager().logout();
                instance.exit();
                instance.showToast("账户已失效，请重新登录");
                instance.startActivity(new Intent(instance, LoginActivity.class));
            }

            @Override
            public void onStartLocation(final WebView webView, final String callbackFunctionName) {
                final WebViewActivity instance = WebViewActivity.getInstance();
                if (instance == null) return;
                final LocationManager locationManager = LocationManager.getInstance();
                locationManager.startBaiduLocation(new BaiduLocationListener() {

                    @Override
                    public void onLocationResult(BDLocation bdLocation) {
                        final LocationInfo info = new LocationInfo();
                        if (bdLocation != null) {
                            int resultCode = bdLocation.getLocType();
                            if (resultCode == BDLocation.TypeGpsLocation || resultCode == BDLocation.TypeNetWorkLocation) {
                                info.setErrorCode(1);
                                info.setErrorMsg("定位成功");
                                LocationBean bean = new LocationBean();
                                bean.setLatitude(bdLocation.getLatitude() + "");
                                bean.setLongitude(bdLocation.getLongitude() + "");
                                bean.setAddress(bdLocation.getLocationDescribe());
                                info.setLocationInfo(bean);
                            } else {
                                info.setErrorCode(0);
                                info.setErrorMsg("定位失败");
                            }
                        } else {
                            info.setErrorCode(0);
                            info.setErrorMsg("定位失败, 未获取经纬度");
                        }

                        webView.post(new Runnable() {
                            @Override
                            public void run() {
                                webView.loadUrl("javascript:" + callbackFunctionName + "('" + JSON.toJSONString(info) + "')");
                            }
                        });

                        locationManager.stopBaiduLocation();
                    }
                });
            }

            @Override
            public void onGetUnread(final WebView webView, String appId, String callbackFunctionName) {
                Logger.e("onGetUnread");
                UnreadCache cache = UnreadManager.getUnreadCache();
                String codes = "";
                if (cache != null && cache.getUnreadMap() != null) {
                    List<String> codeList = cache.getUnreadMap().get(appId);
                    if (codeList != null && codeList.size() > 0) {
                        codes = JSON.toJSONString(codeList);

                    }
                }
                final String jsFunction = "javascript:" + callbackFunctionName + "('" + codes + "')";
                Logger.e("JSBridge", "getUnread callback:" + jsFunction);

                webView.post(new Runnable() {
                    @Override
                    public void run() {
                        webView.loadUrl(jsFunction);
                    }
                });
            }

            @Override
            public void onSetRead(String appId, String code) {
                Logger.e("onSetRead, appId:" + appId + ",code:" + code);
                UnreadManager.setRead(appId, code);
            }
        });
    }

    public static Context getContext(){
        return context;
    }
}
